import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

export interface Device {
  device_id: string;
  name: string;
  classification_name: string;
  classification_code: string;
  specialty: string;
  sub_specialty?: string;
  naming_table?: string;
  position_table?: string;
  base_params_table?: string;
  naming_table_display?: string;
  position_table_display?: string;
  base_params_table_display?: string;
}

export interface DeviceHierarchy {
  classification_name: string;
  specialty: string;
  devices: Device[];
}

// GET /api/device-hierarchy-by-name?specialty=配管专业
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const specialty = searchParams.get('specialty');
    
    const db = getDeviceParameterDb();
    
    // 从devices表获取设备信息，按classification_name分组
    let query = `
      SELECT 
        device_id,
        name,
        classification_name,
        classification_code,
        specialty,
        sub_specialty,
        naming_table_id as naming_table,
        position_table_id as position_table,
        base_params_table_id as base_params_table
      FROM devices 
      WHERE classification_name IS NOT NULL 
        AND classification_name != ''
        AND name IS NOT NULL
        AND name != ''
    `;
    
    const params: any[] = [];
    
    if (specialty) {
      query += ' AND specialty = ?';
      params.push(specialty);
    }
    
    query += ' ORDER BY classification_name, name';
    
    const deviceParameterDb = db as any;
    const stmt = deviceParameterDb.db.prepare(query);
    const devices = stmt.all(...params) as Device[];
    
    // 为每个设备获取表映射信息
    const devicesWithMapping = devices.map(device => {
      console.log('处理设备映射:', device.device_id, device.classification_code);
      
      // 尝试从device_type_mappings获取表映射信息
      const mapping = db.getDeviceTypeMapping(device.classification_code);
      console.log('设备类型映射:', mapping);
      
      if (mapping) {
        // 获取表的描述信息
        const namingTableMeta = db.getTableMetadata(mapping.naming_table);
        const positionTableMeta = db.getTableMetadata(mapping.position_table);
        const baseParamsTableMeta = db.getTableMetadata(mapping.base_params_table);
        
        console.log('表元数据调试:', {
          naming_table: mapping.naming_table,
          namingTableMeta,
          position_table: mapping.position_table,
          positionTableMeta,
          base_params_table: mapping.base_params_table,
          baseParamsTableMeta
        });
        
        const result = {
          ...device,
          naming_table: mapping.naming_table,
          position_table: mapping.position_table,
          base_params_table: mapping.base_params_table,
          naming_table_display: namingTableMeta?.table_description || namingTableMeta?.short_name || extractTableCode(mapping.naming_table),
          position_table_display: positionTableMeta?.table_description || positionTableMeta?.short_name || extractTableCode(mapping.position_table),
          base_params_table_display: `${device.classification_name}基础参数表`
        };
        console.log('使用映射后的设备信息:', result);
        return result;
      }
      
      // 如果没有映射，使用默认的表名
      const defaultTables = {
        naming_table: 'table_c2',      // 默认命名表
        position_table: 'table_c6',    // 默认位置表
        base_params_table: 'table_c494' // 默认基础参数表
      };
      
      // 获取默认表的描述信息
      const defaultNamingTableMeta = db.getTableMetadata(device.naming_table || defaultTables.naming_table);
      const defaultPositionTableMeta = db.getTableMetadata(device.position_table || defaultTables.position_table);
      const defaultBaseParamsTableMeta = db.getTableMetadata(device.base_params_table || defaultTables.base_params_table);
      
      const result = {
        ...device,
        naming_table: device.naming_table || defaultTables.naming_table,
        position_table: device.position_table || defaultTables.position_table,
        base_params_table: device.base_params_table || defaultTables.base_params_table,
        naming_table_display: defaultNamingTableMeta?.table_description || defaultNamingTableMeta?.short_name || extractTableCode(device.naming_table || defaultTables.naming_table),
        position_table_display: defaultPositionTableMeta?.table_description || defaultPositionTableMeta?.short_name || extractTableCode(device.position_table || defaultTables.position_table),
        base_params_table_display: `${device.classification_name}基础参数表`
      };
      console.log('使用默认表名后的设备信息:', result);
      return result;
    });
    
    // 按classification_name分组
    const hierarchyMap = new Map<string, Device[]>();
    
    devicesWithMapping.forEach(device => {
      if (!hierarchyMap.has(device.classification_name)) {
        hierarchyMap.set(device.classification_name, []);
      }
      hierarchyMap.get(device.classification_name)!.push(device);
    });
    
    // 转换为层次结构
    const hierarchies: DeviceHierarchy[] = Array.from(hierarchyMap.entries()).map(([classificationName, devices]) => ({
      classification_name: classificationName,
      specialty: specialty || (devices.length > 0 ? devices[0].specialty : ''),
      devices: devices.sort((a, b) => a.name.localeCompare(b.name))
    }));
    
    return NextResponse.json({
      success: true,
      data: hierarchies.sort((a, b) => a.classification_name.localeCompare(b.classification_name))
    });
    
  } catch (error) {
    console.error('获取设备层次结构失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取设备层次结构失败'
    }, { status: 500 });
  }
}

// 从表名提取显示代码，如 "table_c2" -> "C.2"
function extractTableCode(tableName: string): string {
  if (!tableName) return '';
  const match = tableName.match(/table_c(\d+)/i);
  return match ? `C.${match[1]}` : tableName;
}